package vn.vfriends.mcms.admin.service.impl;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.Status;
import javax.transaction.UserTransaction;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.MessageContext;
import vn.vfriends.mcms.admin.model.Site;
import vn.vfriends.mcms.admin.model.User;
import vn.vfriends.mcms.admin.service.SiteService;
import vn.vfriends.mcms.admin.service.impl.exceptions.IllegalOrphanException;
import vn.vfriends.mcms.admin.service.impl.exceptions.NonexistentEntityException;
import vn.vfriends.mcms.admin.service.impl.exceptions.RollbackFailureException;
import vn.vfriends.mcms.admin.service.impl.exceptions.ViolationException;
import vn.vfriends.mcms.site.ws.SiteWS;
import vn.vfriends.mcms.site.ws.SiteWS_Service;

/**
 *
 * @author tuan@vfriends.vn
 */
public class SiteJpaController implements SiteService {

    @Resource
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "mcmsPU")
    private EntityManagerFactory emf = null;
    @Inject private Validator validator;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    @Override
    public void createSite(Site site) throws RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            Set<ConstraintViolation<Site>> violations = this.validator.validate(site);
            if (violations.size() > 0) {
                ViolationException exception = new ViolationException(violations);
                throw exception;
            }
            
            utx.begin();
            em = getEntityManager();
            em.persist(site);
            utx.commit();
        } catch (ViolationException ve) {
            throw ve;
        } catch (Exception ex) {
            try {
                if (utx.getStatus() == Status.STATUS_ACTIVE) {
                    utx.rollback();
                }
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    @Override
    public void editSite(Site site) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            Set<ConstraintViolation<Site>> violations = this.validator.validate(site);
            if (violations.size() > 0) {
                ViolationException exception = new ViolationException(violations);
                throw exception;
            }
            
            utx.begin();
            em = getEntityManager();
            site = em.merge(site);
            utx.commit();
        } catch (ViolationException ve) {
            throw ve;
        } catch (Exception ex) {
            try {
                if (utx.getStatus() == Status.STATUS_ACTIVE) {
                    utx.rollback();
                }
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = site.getId();
                if (findSite(id) == null) {
                    throw new NonexistentEntityException("The site with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    @Override
    public void destroySite(Long id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Site site;
            try {
                site = em.getReference(Site.class, id);
                site.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The site with id " + id + " no longer exists.", enfe);
            }
            em.remove(site);
            utx.commit();
        } catch (Exception ex) {
            try {
                if (utx.getStatus() == Status.STATUS_ACTIVE) {
                    utx.rollback();
                }
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    @Override
    public List<Site> findSites() {
        return findSites(true, -1, -1);
    }

    @Override
    public List<Site> findSites(int maxResults, int firstResult) {
        return findSites(false, maxResults, firstResult);
    }

    private List<Site> findSites(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Site.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    @Override
    public List<Site> findSitesByUser(User user) {
        EntityManager em = getEntityManager();
        try {
            Query query = em.createNamedQuery("Site.findByUser", User.class);
            query.setParameter("user", user);
            return query.getResultList();
        } finally {
            em.close();
        }
    }
    
    @Override
    public Site findSite(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Site.class, id);
        } finally {
            em.close();
        }
    }

    @Override
    public int getSiteCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Site> rt = cq.from(Site.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
    @Override
    public void deploySite(String siteName) throws Exception {
        SiteWS_Service service = new SiteWS_Service();
        SiteWS siteWS = service.getSiteWSPort();
        Map<String, Object> requestContext = ((BindingProvider)siteWS).getRequestContext();
        
        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        headers.put("USERNAME", Collections.singletonList("wsuser"));
        headers.put("PASSWORD", Collections.singletonList("wsuser"));
        requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
        
        siteWS.deploySite(siteName);
    } 

    @Override
    public Site findSiteByName(String name) {
        EntityManager em = getEntityManager();
        try {
            Query query = em.createNamedQuery("Site.findByName", Site.class);
            query.setParameter("name", name);
            List<Site> siteList = (List<Site>) query.getResultList();
            if (siteList != null && !siteList.isEmpty()) {
                return siteList.get(0);
            } else {
                return null;
            }
        } finally {
            em.close();
        }
    }
    
}
